<template>
  <FeatureAttention
    :feature="PlanFeature.FEATURE_RISK_ASSESSMENT"
    class="mb-4"
  />

  <div class="w-full flex flex-col gap-y-4 text-sm">
    <div class="textinfolabel">
      {{ $t("custom-approval.risk.description") }}
      <LearnMoreLink
        url="https://docs.bytebase.com/administration/risk-center?source=console"
      />
    </div>
    <RiskCenter v-if="state.ready" />
    <div v-else class="w-full py-16 flex justify-center items-center">
      <BBSpin />
    </div>
  </div>

  <RiskDialog />

  <FeatureModal
    :feature="PlanFeature.FEATURE_RISK_ASSESSMENT"
    :open="state.showFeatureModal"
    @cancel="state.showFeatureModal = false"
  />
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, toRef } from "vue";
import { BBSpin } from "@/bbkit";
import {
  RiskCenter,
  RiskDialog,
  provideRiskCenterContext,
} from "@/components/CustomApproval/Settings/components/RiskCenter";
import { provideRiskFilter } from "@/components/CustomApproval/Settings/components/common";
import { FeatureAttention, FeatureModal } from "@/components/FeatureGuard";
import LearnMoreLink from "@/components/LearnMoreLink.vue";
import { featureToRef, useRiskStore } from "@/store";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { hasWorkspacePermissionV2 } from "@/utils";

interface LocalState {
  ready: boolean;
  showFeatureModal: boolean;
}

const state = reactive<LocalState>({
  ready: false,
  showFeatureModal: false,
});
const hasRiskAssessmentFeature = featureToRef(
  PlanFeature.FEATURE_RISK_ASSESSMENT
);

const allowAdmin = computed(() => {
  return hasWorkspacePermissionV2("bb.risks.update");
});

provideRiskFilter();
provideRiskCenterContext({
  hasFeature: hasRiskAssessmentFeature,
  showFeatureModal: toRef(state, "showFeatureModal"),
  allowAdmin,
  ready: toRef(state, "ready"),
  dialog: ref(),
});

onMounted(async () => {
  try {
    await useRiskStore().fetchRiskList();
    state.ready = true;
  } catch {
    // nothing
  }
});
</script>
